package com.jyw.business.de.expand.task;

import cn.hutool.core.util.StrUtil;
import com.jyw.business.de.constant.DemandStateConstant;
import com.jyw.business.de.domain.DeDemandInfo;
import com.jyw.business.de.service.IDeDemandInfoService;
import com.jyw.business.de.service.ISysDemandReminderConfigService;
import com.jyw.business.obstacles.service.IObsOrderMessageService;
import com.jyw.common.constant.CacheConstants;
import com.jyw.common.core.redis.RedisCache;
import com.jyw.common.utils.DateUtils;
import com.jyw.system.domain.vo.SysDemandReminderConfigVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 需求超时未分配提醒
 */
@Component("DeDemandAllocationTask")
@Slf4j
public class DeDemandAllocationTask {

    @Resource
    private IDeDemandInfoService deDemandInfoService;

    @Resource
    private ISysDemandReminderConfigService configService;

    @Resource
    private IObsOrderMessageService messageService;

    @Resource
    private RedisCache redisCache;

    public void remind(){
        SysDemandReminderConfigVo config = configService.getDefaultConfig();
        //超时未分配开关
        if (config.getDemandDispatchTimeoutRemind()) {
            Date timeOut = DateUtils.addMinutes(DateUtils.getNowDate(), -config.getDemandDispatchTimeoutMinute());
            List<DeDemandInfo> list = deDemandInfoService.lambdaQuery()
                    .eq(DeDemandInfo::getDemandState, DemandStateConstant.ALLOCATION)
                    .le(DeDemandInfo::getWaitAllocationTime, timeOut)
                    .list();
            if(!CollectionUtils.isEmpty(list)&&!redisCache.hasKey(CacheConstants.DE_WAIT_ALLOCATION_KEY)){
                messageService.sendServiceMsg(StrUtil.format("今日共有{}个需求超时待派单,请尽快处理",list.size()));
                redisCache.setCacheObject(CacheConstants.DE_WAIT_ALLOCATION_KEY,list,config.getDemandDispatchTimeoutInterval(), TimeUnit.MINUTES);
            }
        }
    }
}
